#include "main.h"
#include <iostream>
#include "curl-8.8.0/include/curl/curl.h"

#include "asio.hpp"

typedef union
{
    struct sockaddr     sa;
    struct sockaddr_in  sin;
    struct sockaddr_in6 sin6;
} sockaddr_u;


int main(int argc, char *argv[])
{

    curl_httppost httppost;
    try
    {
        asio::io_context io_context;

        std::string ip_address_str = "::";
        asio::ip::address ip_address = asio::ip::make_address(ip_address_str);
        if (ip_address.is_v4() == false && ip_address.is_v6() == false)
        {
            return 1;
        }

        asio::ip::udp::endpoint endpoint(ip_address, 8088);
        
        asio::ip::udp::socket socket(io_context, endpoint);
        if (socket.is_open() == false)
        {
            printf("udp socket open error\n");
            return 1;
        }
        printf("udp socket open success\n");

        while(true)
        {
            char dataBuff[2048];
            asio::ip::udp::endpoint remote_endpoint;
            size_t length = socket.receive_from(asio::buffer(dataBuff, sizeof(dataBuff)), remote_endpoint);

            std::cout << remote_endpoint.address().to_string() << ":" << remote_endpoint.port() << std::endl;


            // sockaddr_u *sockAddrData = (sockaddr_u *)remote_endpoint.data();
            // if (sockAddrData->sa_family == AF_INET)
            // {
            //     for (int32_t i = 0; i < 4; i++)
            //     {
            //         sockAddrData->sin.sin_addr.S_un.S_un_b.s_b1
            //         printf();
            //     }
            // }



            for (uint16_t index = 0; index < length; index++)
            {
                printf("%02X ", dataBuff[index]);
            }
            printf("\n");

            socket.send_to(asio::buffer(dataBuff, length), remote_endpoint);
        }
    }
    catch(const std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << '\n';
    }

    return 0;
}
